package com.ml.shs.aspect;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Aspect
@Component
public class LoginAspect {

    @Autowired
    HttpSession session;

    @Pointcut("@annotation(com.ml.shs.annotation.LoginAnnotation)")
    public void LoginAspect() {

    }

    @Around("LoginAspect()")
    public Object before(ProceedingJoinPoint joinPoint){
        try {
            Object account = session.getAttribute("account");
            Object ret = null;
            if (account == null) {
                HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
                response.sendError(401,"needLogin");
            }else{
                ret = joinPoint.proceed();
            }
            return ret;
        }catch (Throwable e){
            e.printStackTrace();
            return null;
        }
    }
}
